package org.elec.mac.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.constants.Constants;
import org.elec.mac.entity.*;
import org.elec.mac.service.SDeviceService;
import org.elec.mac.service.SDeviceTechService;
import org.elec.mac.service.SMachineService;
import org.elec.mac.service.SMachineTechService;
import org.elec.mac.utils.JSONUtil;
import org.elec.mac.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
public class DeviceTechController extends BaseController {

    @Autowired
    private SDeviceTechService deviceTechService;

    @Autowired
    private SDeviceService deviceService;

    @Autowired
    private SMachineService machineService;

    @Autowired
    private SMachineTechService machineTechService;

    @RequestMapping(value = "/devicetech_list.do")
    public String deviceTechListHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                        @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                        @RequestParam(value = "deviceid", required = false) String deviceid,
                                        @RequestParam(value = "limit", required = false) String limit,
                                        @RequestParam(value = "page", required = false) String page) throws IOException {
        Map<String, Object> param = new HashMap<>();
        param.put("did", Utils.parseLong(deviceid, 0L));
        param.put("flag",1);
        List<SDeviceTech> deviceTechList = deviceTechService.list(param);
        model.put("deviceTechList", deviceTechList);
        param.clear();
        param.put("id", Utils.parseLong(deviceid, 0L));
        SDevice sDevice = deviceService.get(param);
        model.put("sDevice", sDevice);
//        if("page".equals(action)) {
//            PageProperty pp = new PageProperty();
//            pp.getParamMap().put("did", Utils.parseLong(deviceid, 0L));
//            Map<String, Object> map = new HashMap<String, Object>();
//            try {
//                this.setPageInfo(request.getCookies(), pp, limit, page);
//                PageList<SDeviceTech> lintPageList = deviceTechService.getPageList(pp);
//                map.put("success", true);
//                map.put("records", lintPageList.getRecords());
//                map.put("recordsTotal", lintPageList.getTotalRecords());
//                map.put("recordsFiltered", lintPageList.getTotalRecords());
//
//                model.addAttribute("success", true);
//                model.addAttribute("records", lintPageList.getRecords());
//                model.addAttribute("recordsTotal", lintPageList.getTotalRecords());
//                model.addAttribute("recordsFiltered", lintPageList.getTotalRecords());
//
//
//            } catch(Exception ex) {
//                log.error("设备列表获取错误", ex);
//                map.put("success", false);
//                map.put("msg", "设备列表获取错误");
//            }
//            response.getWriter().write(JSONUtil.map2json(map));
//            return "/device/device_tech_list";
//       }
       model.put("deviceid", Utils.parseLong(deviceid, 0L));
       return "/device/device_tech_list";
    }

    @RequestMapping(value = "/devicetech_add.do")
    public void deviceTechAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                     @RequestParam(value = "action", required = false, defaultValue = "") String action)
            throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("do".equals(action)) {
            try {
                Long did = Utils.parseLong(this.getParameter(request, "deviceid"), 0L);
                String tkey = this.getParameter(request, "tkey");
                Long minval = Utils.parseLong(this.getParameter(request, "minval"), Constants.UnknowLong);
                Long maxval = Utils.parseLong(this.getParameter(request, "maxval"), Constants.UnknowLong);
                String remark = this.getParameter(request, "remark");

                if(did == 0L) {
                    result.setSuccess(false);
                    result.setMsg("设备Id不能为空");
                }
                if(StringUtils.isBlank(tkey)) {
                    result.setSuccess(false);
                    result.setMsg("参数标识不能为空");
                }
                if(minval == Constants.UnknowLong) {
                    result.setSuccess(false);
                    result.setMsg("最低阀值不能为空");
                }
                if(maxval == Constants.UnknowLong) {
                    result.setSuccess(false);
                    result.setMsg("最高阀值不能为空");
                }

                Map<String, Object> params = new HashMap<>();
                params.put("did", did);
                params.put("tkey", tkey);
                params.put("flag", 1);
                SDeviceTech tech = deviceTechService.get(params);
                if(null != tech){
                    result.setSuccess(false);
                    result.setMsg("参数标识已存在");
                }
                if(result.isSuccess()) {
                    SDeviceTech deviceTech = new SDeviceTech();
                    deviceTech.setDid(did);
                    deviceTech.setTkey(tkey);
                    deviceTech.setMinval(minval);
                    deviceTech.setMaxval(maxval);
                    deviceTech.setRemark(remark);
                    deviceTech.setFlag(true);
                    deviceTechService.insert(deviceTech);
                    log.info("设备参数新增");
                    long dtid = deviceTech.getId();
                    Map<String, Object> param = new HashMap<>();
                    param.put("did", Utils.parseLong(this.getParameter(request, "deviceid"), 0L));
                    List<SMachine> machines = machineService.list(param);
                    if(machines != null && machines.size() > 0) {
                        List<SMachineTech> list = new ArrayList<SMachineTech>();
                        for (SMachine m : machines) {
                            SMachineTech mach = new SMachineTech();
                            mach.setMachid(m.getId());
                            mach.setDtid(dtid);
                            mach.setCval(minval);
                            list.add(mach);
                        }
                        machineTechService.insertMachineTechBatch(list);
                        log.info("机台参数新增");
                    }
                }
            } catch(Exception ex) {
                log.error("设备参数新增错误", ex);
                result.setSuccess(false);
                result.setMsg("设备参数新增错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }



    @RequestMapping(value = "/devicetech_edit.do")
    public void deviceTechEditHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                      @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                      @RequestParam(value = "id", required = false, defaultValue = "") String id)
            throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("edit".equals(action)) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("id", Utils.parseLong(id, 0L));
                SDeviceTech deviceTech = deviceTechService.get(params);
                result.getBody().put("deviceTech", deviceTech);
                log.info("设备参数修改开启");
            } catch(Exception ex) {
                log.error("设备参数修改开启错误", ex);
                result.setSuccess(false);
                result.setMsg("设备参数修改开启错误");
            }
        }
        if("doEdit".equals(action)) {
            try {
                Long did = Utils.parseLong(this.getParameter(request, "did"), 0L);
                String tkey = this.getParameter(request, "tkey");
                Long minval = Utils.parseLong(this.getParameter(request, "minval"), Constants.UnknowLong);
                Long maxval = Utils.parseLong(this.getParameter(request, "maxval"), Constants.UnknowLong);
                String remark = this.getParameter(request, "remark");

                if(did == 0L) {
                    result.setSuccess(false);
                    result.setMsg("设备Id不能为空");
                }
                if(StringUtils.isBlank(tkey)) {
                    result.setSuccess(false);
                    result.setMsg("参数标识不能为空");
                }
                if(minval == Constants.UnknowLong) {
                    result.setSuccess(false);
                    result.setMsg("最低阀值不能为空");
                }
                if(maxval == Constants.UnknowLong) {
                    result.setSuccess(false);
                    result.setMsg("最高阀值不能为空");
                }


                Map<String, Object> params = new HashMap<>();
                params.put("tkey", tkey);
                params.put("flag", 1);
                int tKeyCount = deviceTechService.getCount(params);

                Map<String, Object> par = new HashMap<>();
                par.put("id", Utils.parseLong(id, 0L));
                String key  = deviceTechService.get(par).getTkey();

                if(tKeyCount > 0 && !tkey.equals(key)){
                    result.setSuccess(false);
                    result.setMsg("参数标识已存在");
                }

                if(result.isSuccess()) {
                    SDeviceTech deviceTech = new SDeviceTech();
                    deviceTech.setId(Utils.parseLong(id, 0L));
                    deviceTech.setDid(did);
                    deviceTech.setTkey(tkey);
                    deviceTech.setMinval(minval);
                    deviceTech.setMaxval(maxval);
                    deviceTech.setRemark(remark);
                    deviceTech.setFlag(true);
                    deviceTechService.update(deviceTech);
                    log.info("设备修改");
                }
            } catch(Exception ex) {
                log.error("设备修改错误", ex);
                result.setSuccess(false);
                result.setMsg("设备修改错误");
            }
        }
        if("doDelete".equals(action)) {
            try {
                SDeviceTech deviceTech = new SDeviceTech();
                deviceTech.setId(Utils.parseLong(id, 0L));
                deviceTech.setFlag(false);
                deviceTechService.update(deviceTech);
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("dtid",Utils.parseLong(id, 0L));
                machineTechService.deleteMachineTech(param);
                log.info("设备删除");
            } catch(Exception ex) {
                log.error("设备删除错误", ex);
                result.setSuccess(false);
                result.setMsg("设备删除错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }
}
